//
//  ReportDeviceVC.m
//  efairy
//  设备报表 统计每次报警的时间段、峰值 、峰值时间、风险评估等
//  Created by 李锋 on 2019/3/21.
//  Copyright © 2019年 East. All rights reserved.
//

#import "ReportDeviceVC.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAModel.h"
#import <MJRefresh.h>
#import "ReportProjectDeviceInfoCell.h"
#import "ReportProjectDeviceAlarmInfoCell.h"

@interface ReportDeviceVC ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property (nonatomic, strong) MJRefreshComponent * refreshViewComponent;
@property(nonatomic,strong)UITableView *tableView;
@property (nonatomic, assign) int pageIndex;
@property (nonatomic, strong) NSString *alarmType;
@property (nonatomic, strong) NSString *riskType;
@property (nonatomic, strong) NSString *alarmName;
@property (nonatomic, strong) NSString *riskName;
@property(nonatomic,strong)NSMutableArray<ReportDeviceAlarmInfo *> *dataArray;

@property(nonatomic,strong)UIView *mTypeUIView;
@property(nonatomic,strong)UIImageView *mTypeImage;

@property(nonatomic,strong)UILabel *mAlarmType;//报警类型
@property(nonatomic,strong)UILabel *mAlarmDates;  // 报警时间段
@property(nonatomic,strong)UILabel *mScore;//峰值分数；

@property(nonatomic,strong)UIView *mRiskUIView;
@property(nonatomic,strong)UIImageView *mRiskImage;
@property(nonatomic,strong)UILabel *mRisk;//风险评估
@property(nonatomic,strong)UIView *mTitleView;
@property(nonatomic,strong)UIView *cellAlarmTypeView;
@end

@implementation ReportDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageIndex = 1;
    _alarmType = @"";
    _riskType = @"";
    _alarmName = @"报警类型";
    _riskName = @"风险评估";
    [self setNavigationBar];
    [self initview];
}



-(void)setNavigationBar{
    self.navigationItem.title=@"设备报告详情";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"global_nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(backVC)];
}

- (void)backVC {
    //返回上一界面
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initview{
    float barHeight =  self.navigationController.navigationBar.frame.size.height;
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, barHeight+statusBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT-barHeight-statusBarHeight)];
    _tableView.backgroundColor = ColorFromRGB(0xeff0f4);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;//设置分割线为隐藏
    __weak  typeof(self) weakSelf = self;
    //    //下拉刷新
    //        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //            weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
    //            weakSelf.pageIndex = 1;
    ////            [weakSelf queryReportProjectInfo:YES];
    //        }];
    
    //上啦刷新
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_footer;
        weakSelf.pageIndex = weakSelf.pageIndex + 1;
        [weakSelf queryDeviceAlarmInfoList:NO];
    }];
    
    
    _mTitleView = [[UIView alloc]initWithFrame:CGRectMake(0, barHeight+statusBarHeight, SCREEN_WIDTH, 50)];
    _mTitleView.backgroundColor = [UIColor whiteColor];
    
    _mTypeUIView = [[UIView alloc]init];
    _mTypeUIView.layer.borderColor = [ColorFromRGB(0xB3B8BE)CGColor];
    _mTypeUIView.layer.borderWidth = 1.0f;
    UITapGestureRecognizer *alarmTypeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onclickAlarmType:)];
    [_mTypeUIView addGestureRecognizer:alarmTypeTap];
    
    _mTypeImage = [[UIImageView alloc]init];
    _mTypeImage.image = [UIImage imageNamed:@"icon_arrow_bottom"];
    
    _mAlarmType = [[UILabel alloc]init];//报警类型
    _mAlarmType.text = @"报警类型";
    _mAlarmType.textColor = ColorFromRGB(0x333333);
    _mAlarmType.font = [UIFont systemFontOfSize:12.f];
    //    _mAlarmType = [ColorFromRGB(0xB3B8BE)CGColor];
    //    _mAlarmType = 1.0f;
    _mAlarmType.textAlignment = NSTextAlignmentCenter;
    _mAlarmType.numberOfLines = 2;
    
    [_mTypeUIView sd_addSubviews:@[_mAlarmType,_mTypeImage]];
    _mAlarmType.sd_layout.leftSpaceToView(_mTypeUIView, 0).rightSpaceToView(_mTypeUIView, 0).heightIs(30)
    .topSpaceToView(_mTypeUIView, 4);
    _mTypeImage.sd_layout.widthIs(12).heightIs(8).topSpaceToView(_mAlarmType, 2).leftSpaceToView(_mTypeUIView, (44-12)/2);
    
    
    
    
    _mAlarmDates = [[UILabel alloc]init];  // 报警时间段
    _mAlarmDates.text = @"报警时间段";
    _mAlarmDates.textColor = ColorFromRGB(0x333333);
    _mAlarmDates.font = [UIFont systemFontOfSize:12.f];
    _mAlarmDates.layer.borderColor = [ColorFromRGB(0xB3B8BE)CGColor];
    _mAlarmDates.layer.borderWidth = 1.0f;
    _mAlarmDates.textAlignment = NSTextAlignmentCenter;
    _mAlarmDates.numberOfLines = 2;
    
    _mScore = [[UILabel alloc]init];//峰值分数；
    _mScore.text = @"峰值分数";
    _mScore.textColor = ColorFromRGB(0x333333);
    _mScore.font = [UIFont systemFontOfSize:12.f];
    _mScore.layer.borderColor = [ColorFromRGB(0xB3B8BE)CGColor];
    _mScore.layer.borderWidth = 1.0f;
    _mScore.textAlignment = NSTextAlignmentCenter;
    _mScore.numberOfLines = 2;
    
    
    
    _mRiskUIView = [[UIView alloc]init];
    _mRiskUIView.layer.borderColor = [ColorFromRGB(0xB3B8BE)CGColor];
    _mRiskUIView.layer.borderWidth = 1.0f;
    UITapGestureRecognizer *riskTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onclickRisk:)];
    [_mRiskUIView addGestureRecognizer:riskTap];
    
    _mRiskImage = [[UIImageView alloc]init];
    _mRiskImage.image = [UIImage imageNamed:@"icon_arrow_bottom"];
    
    _mRisk = [[UILabel alloc]init];//风险评估
    _mRisk.text = @"风险评估";
    _mRisk.textColor = ColorFromRGB(0x333333);
    _mRisk.font = [UIFont systemFontOfSize:12.f];
    _mRisk.textAlignment = NSTextAlignmentCenter;
    _mRisk.numberOfLines = 2;
    
    [_mRiskUIView sd_addSubviews:@[_mRisk,_mRiskImage]];
    _mRisk.sd_layout.leftSpaceToView(_mRiskUIView, 0).rightSpaceToView(_mRiskUIView, 0).heightIs(30)
    .topSpaceToView(_mRiskUIView, 4);
    _mRiskImage.sd_layout.widthIs(12).heightIs(8).topSpaceToView(_mRisk, 2).leftSpaceToView(_mRiskUIView, (44-12)/2);
    
    [_mTitleView sd_addSubviews:@[_mTypeUIView,_mAlarmDates,_mScore,_mRiskUIView]];
   
   
    _mTypeUIView.sd_layout.widthIs(44).heightIs(50).leftSpaceToView(_mTitleView, -1);
    
    _mAlarmDates.sd_layout.widthIs((SCREEN_WIDTH-88)/2+10+4).heightIs(50).leftSpaceToView(_mTypeUIView, -1);
    
    _mScore.sd_layout.widthIs((SCREEN_WIDTH-88)/2-10).heightIs(50).leftSpaceToView(_mAlarmDates, -1);
    
    _mRiskUIView.sd_layout.widthIs(44).heightIs(50).leftSpaceToView(_mScore, -1);
    _mTitleView.hidden = YES;
    [self.view sd_addSubviews:@[_tableView,_mTitleView]];
    [self.tableView.mj_footer resetNoMoreData];
    [self queryDeviceAlarmInfoList:YES];
    
}


-(void)onclickAlarmType:(id)tap{
    [self jumpToSelectAlarmHandle];
}

-(void)onclickRisk:(id)tap{
     [self jumpToSelectRiskHandle];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(_cellAlarmTypeView){
        if(scrollView.contentOffset.y > _cellAlarmTypeView.frame.origin.y+1){
            if(_mTitleView.hidden){
                _mTitleView.hidden = NO;
            }
        }else if(scrollView.contentOffset.y < _cellAlarmTypeView.frame.origin.y){
            if(!_mTitleView.hidden){
                _mTitleView.hidden = YES;
            }
        }
    }
    
    
}

//停止刷新头部或者底部
- (void)tableViewEndRefresh:(BOOL)isHeader {
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

#pragma UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(_dataArray && _dataArray.count > 0){
        return _dataArray.count +1;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        ReportProjectDeviceInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportProjectDeviceInfoCell" description]];
        if(!cell){
            cell = [[ReportProjectDeviceInfoCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            _cellAlarmTypeView = cell.alarmTypeUIView;
            cell.chooseAlarmTypeBlock = ^{
                [self jumpToSelectAlarmHandle];
            };
            
            cell.chooseRiskTypeBlock = ^{
                [self jumpToSelectRiskHandle];
            };
           
            
        }
        [cell setDataModel:_deviceInfoMode typeName:_alarmName riskName:_riskName];
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }else{
        ReportProjectDeviceAlarmInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"ReportProjectDeviceAlarmInfoCell" description]];
        if(!cell){
            cell = [[ReportProjectDeviceAlarmInfoCell alloc]init];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        [cell setDataModel:_dataArray[indexPath.section-1]];
        [cell useCellFrameCacheWithIndexPath:indexPath tableView:tableView];
        return cell;
    }
   
}

#pragma UITableViewDelegate

////cell自适应高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
}

//section header高度设置
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    if(section == 1){
//        return 8.0f;
//    }
    return 0.0001;
}

//section footer高度设置
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

//设置section中header的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//设置sectin中footer的view
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc]init];
}

//点击cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

//查询设备报警列表信息
-(void)queryDeviceAlarmInfoList:(BOOL)isHeader{
    
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    NSDictionary *params =  @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                              @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                              @"efairyreport_id":_reportId == nil ?@"":self.reportId,//报警id
                              @"efairyproject_id":_projectId,//项目编号
                              @"efairydevice_id":_deviceInfoMode.efairydevice_id,//设备编号
                              @"alarm_id":_alarmType,//报警类型0-离线 1-火警 2-预警 3-故障 4-启动 5-屏蔽 6-正常，不传则返回所有
                              @"start_time":@"",//报警开始时间不传则不筛选
                              @"end_time":@"",//报警结束时间不传则不筛选
                              @"risk_evaluation":_riskType,//"风险评估等级，1-高度危险 2-中度危险 3-危险 不传则返回所有"
                              @"page":@(_pageIndex),
                              @"size":@"20"
                              };
    
    NSLog(@"设备报表列表请求参数：%@",params);
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance]GET:[ApiManager ApiProjectDeviceAlarmList] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task,id _Nullable responseObject){
        NSLog(@"获取的设备报表列表%@",responseObject);
        [hud hideAnimated:YES];
        [self tableViewEndRefresh:NO];
        ReportDeviceAlarmDetailListMoel *model=  [ReportDeviceAlarmDetailListMoel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        if( model.efairydevice_alarm_info_list){
            if(isHeader){
                _dataArray = model.efairydevice_alarm_info_list;
            }else{
                if(_dataArray){
                    [_dataArray addObjectsFromArray:model.efairydevice_alarm_info_list];
                }
            }
            if(_dataArray.count >= model.total_rows){
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [self.tableView.mj_footer resetNoMoreData];
            }

        }
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *_Nullable task,NSError * _Nullable error){
        NSLog(@"错误信息：%@",error);
        [hud hideAnimated:YES];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


- (void)jumpToSelectAlarmHandle {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"全部" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _alarmType = @"";
        _alarmName = @"报警类型";
       [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"火警" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _alarmType = @"1";
        _alarmName = @"火警";
        [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"预警" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _alarmType = @"2";
        _alarmName = @"预警";
        [self clearTableViewData];
    }]];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:@"故障" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _alarmType = @"3";
        _alarmName = @"故障";
        [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (void)jumpToSelectRiskHandle {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"全部" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _riskType = @"";
        _riskName = @"风险评估";
        [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"高度危险" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _riskType = @"1";
        _riskName = @"高度危险";
        [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"中度危险" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _riskType = @"2";
        _riskName = @"中度危险";
         [self clearTableViewData];
    }]];
    
    [alertVC addAction:[UIAlertAction actionWithTitle:@"危险" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pageIndex = 1;
        _riskType = @"3";
        _riskName = @"危险";
        [self clearTableViewData];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

-(void)clearTableViewData{
    [_dataArray removeAllObjects];
    [self.tableView reloadData];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       [self queryDeviceAlarmInfoList:YES];
    });
}

@end
